from socketserver import BaseRequestHandler, TCPServer, ThreadingTCPServer, BaseServer
from threading import Thread
import zmq
import configparser
import os
import json
import time
import traceback

class EchoHandler(BaseRequestHandler):
    def handle(self):
        print('socket来源IP和端口：', self.client_address)
        source_ip = self.client_address[0]
        source_port = self.client_address[1]
        self.thread_communication(source_ip)
        
    def thread_communication(self, source_ip):
        context = zmq.Context()
        global config
        config_file = r'update/tools/config.ini'
        config = configparser.ConfigParser()
        config.read(config_file)
        try:
            thread_socket_host = config.get('update','server_ip')
            thread_socket_post1 = config.get('update','thread_req1_port')
            thread_socket_post2 = config.get('update', 'thread_req2_port')

            #thread_logo = config.get('ports','thread_logo_1')
            thread_socket = context.socket(zmq.REQ)
            thread_socket.connect("tcp://%s:%s" % (thread_socket_host, thread_socket_post1))
            thread_socket.send_string(source_ip)
            print('发送连接ip')
            msg = thread_socket.recv_string()
            print('开始发送包')
            endmsg = self.send_zip(json.loads(msg))
            thread_socket.close()

            thread_socket_2 = context.socket(zmq.REQ)
            thread_socket_2.connect("tcp://%s:%s" % (thread_socket_host, thread_socket_post2))
            thread_socket_2.send_string(endmsg)
            thread_socket_2.close()
            context.destroy()
        except BaseException as b:  # 所有异常的基类
            print('thread_communication str(e):\t\t', str(b))  # 简单
            print('thread_communication repr(e):\t', repr(b))  # 较简单
            print('thread_communication traceback.print_exc(): %s' % traceback.print_exc())  # 最详细
            os._exit(3)
        except:
            print('deployment_zip traceback.print_exc(): %s' % traceback.print_exc())  # 最详细
            os._exit(3)
    
    def send_zip(self,return_zcell_json):
        global Equipment
        Equipment_file = r'update/tools/Equipment.ini'
        Equipment = configparser.ConfigParser()
        Equipment.read(Equipment_file)
        zcell_name = ''
        while True:
            try:
                msg = self.request.recv(7)
                if not msg:
                    break
                else:
                    zcell_name = msg.decode('utf-8')
                    status = 0
                    for single_zcell_json in return_zcell_json:
                        if single_zcell_json["id"] == zcell_name:
                            for i in single_zcell_json["module"]:
                                status = 1
                                if i.endswith('zip'):
                                    self.read_zip(i,1)
                                else:
                                    self.read_zip(i,2)
                            self.request.send(b'1')
                            break
                    if status == 0:
                        print("接收到的zcell名称与匹配更新的不一致")
                        zcell_name = 'error'
                        break
                    break
            except BaseException as b:  # 所有异常的基类
                print('thread_communication str(e):\t\t', str(b))  # 简单
                print('thread_communication repr(e):\t', repr(b))  # 较简单
                print('thread_communication traceback.print_exc(): %s' % traceback.print_exc())  # 最详细
                os._exit(3)
            except:
                print('deployment_zip traceback.print_exc(): %s' % traceback.print_exc())  # 最详细
                os._exit(3)
        return zcell_name
    
    def read_zip(self,module_zip,status):
        page_file = config.get('service_side', 'updata_file')
        f2 = ''
        zip_module = ''
        try:
            if status == 1:
                print('更新全部')
                zip_module = module_zip
                zip_name = zip_module.split('.')
                zip_file = Equipment.get("Equipment2", zip_name[0])
                f1 = os.path.join(page_file, zip_file)
                f2 = os.path.join(f1, zip_module)
            elif status == 2:
                print('单独更新')
                module_name = module_zip[:-5] + ".zip"
                zip_file = Equipment.get("Equipment2", module_zip[:-5])
                zip_module = module_name + "|" + module_zip
                f1 = os.path.join(page_file, zip_file)
                f2 = os.path.join(f1, module_name)
                print('发送数据包: %s' % zip_module)
                print('压缩包路径：%s' % f2)
            self.request.send(bytes(str(len(zip_module)), encoding="utf8"))
            self.request.send(bytes(zip_module, encoding="utf8"))
            with open(f2, 'rb') as e:
                for data in e:
                    self.request.send(data)
            e.close()
            time.sleep(6)
            self.request.send(b'next')

        except BaseException as b:  # 所有异常的基类
            print('thread_communication str(e):\t\t', str(b))  # 简单
            print('thread_communication repr(e):\t', repr(b))  # 较简单
            print('thread_communication traceback.print_exc(): %s' % traceback.print_exc())  # 最详细
            os._exit(3)
        except:
            print('deployment_zip traceback.print_exc(): %s' % traceback.print_exc())  # 最详细
            os._exit(3)
        return

